import requests
import json
from typing import Optional, Dict, Any
from src.common.logs import *

logger = get_logger()
class LoginAPI:
    """
    登录接口封装类
    对应API: https://stress-sea-user.lingmouai.com/user/v3/system/login
    """

    def __init__(self, base_url: str = "https://stress-sea-user.lingmouai.com"):
        """
        初始化登录API

        Args:
            base_url: API基础URL，默认为截图中的域名
        """
        self.base_url = base_url.rstrip('/')  # 移除末尾可能存在的斜杠
        self.login_url = f"{self.base_url}/user/v3/system/login"
        self.token = None
        self.session = requests.Session()
        
        # 初始化日志记录器
        self.logger = get_logger(module_name='login_api')

        # 设置请求头
        self.headers = {
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        }

    def login(self, account,password) -> Dict[str, Any]:
        """
        执行登录操作

        Args:
            account: 账号，默认为截图中的Alltest
            password: 密码，默认为截图中的Abcd1234.

        Returns:
            包含登录响应数据的字典
        """
        # 构建请求体
        payload = {
            "account": account,
            "password": password
        }

        try:
            # 发送POST请求
            self.logger.info(f"开始登录请求，账号: {account}")
            response = self.session.post(
                self.login_url,
                headers=self.headers,
                json=payload,
                timeout=10
            )
            self.logger.info(f"登录响应状态码: {response.status_code}")


            # 检查响应状态
            if response.status_code == 200:
                try:
                    result = response.json()
                except json.JSONDecodeError:
                    # 如果响应不是有效的JSON，返回原始文本
                    return {
                        "success": False,
                        "status_code": response.status_code,
                        "error": "响应不是有效的JSON",
                        "response_text": response.text,
                        "token": None
                    }

                # 提取并保存token
                token = None
                if 'data' in result and 'token' in result['data']:
                    token = result['data']['token']
                elif 'token' in result:
                    token = result['token']

                self.token = token
                
                # 打印token信息
                if token:
                    self.logger.info(f"登录成功，获取到token: {token}")
                    # 安全地显示token前几位和后几位
                    if len(token) > 20:
                        token_display = f"{token[:10]}...{token[-10:]}"
                        self.logger.info(f"Token摘要: {token_display}")
                else:
                    self.logger.warning("登录响应中未找到token")
                    self.logger.debug(f"完整响应数据: {result}")

                return {
                    "success": True,
                    "status_code": response.status_code,
                    "data": result,
                    "token": token
                }
            else:
                # 对于非200响应，尝试解析JSON错误信息
                try:
                    error_data = response.json()
                    error_msg = error_data.get('message', response.text)
                except json.JSONDecodeError:
                    error_msg = response.text

                return {
                    "success": False,
                    "status_code": response.status_code,
                    "error": error_msg,
                    "token": None
                }

        except requests.exceptions.RequestException as e:
            return {
                "success": False,
                "status_code": None,
                "error": f"请求异常: {str(e)}",
                "token": None
            }


    def get_token(self) -> Optional[str]:
        """
        获取当前token

        Returns:
            当前保存的token，如果未登录则为None
        """
        return self.token

    def set_auth_header(self, headers: Dict[str, str] = None) -> Dict[str, str]:
        """
        设置认证头部

        Args:
            headers: 现有的头部字典，如果为None则创建新字典

        Returns:
            包含认证头部的字典
        """
        if headers is None:
            headers = {}

        if self.token:
            # 尝试不同的认证方式
            headers["Authorization"] = f"Bearer {self.token}"
            headers["token"] = self.token

        return headers

    def call_authenticated_api(self, url: str, method: str = "GET", data: Dict = None) -> Dict[str, Any]:
        """
        调用需要认证的API

        Args:
            url: API地址
            method: 请求方法 (GET, POST, PUT, DELETE等)
            data: 请求数据

        Returns:
            API响应数据
        """
        if not self.token:
            return {
                "success": False,
                "error": "未登录，请先调用login方法"
            }

        # 设置认证头部
        headers = self.set_auth_header(self.headers.copy())

        try:
            if method.upper() == "GET":
                response = self.session.get(url, headers=headers, timeout=10)
            elif method.upper() == "POST":
                response = self.session.post(url, headers=headers, json=data, timeout=10)
            elif method.upper() == "PUT":
                response = self.session.put(url, headers=headers, json=data, timeout=10)
            elif method.upper() == "DELETE":
                response = self.session.delete(url, headers=headers, timeout=10)
            else:
                return {
                    "success": False,
                    "error": f"不支持的HTTP方法: {method}"
                }

            # 处理响应
            if 200 <= response.status_code < 300:
                try:
                    return {
                        "success": True,
                        "status_code": response.status_code,
                        "data": response.json()
                    }
                except json.JSONDecodeError:
                    return {
                        "success": True,
                        "status_code": response.status_code,
                        "data": response.text
                    }
            else:
                try:
                    error_data = response.json()
                    error_msg = error_data.get('message', response.text)
                except json.JSONDecodeError:
                    error_msg = response.text

                return {
                    "success": False,
                    "status_code": response.status_code,
                    "error": error_msg
                }

        except requests.exceptions.RequestException as e:
            return {
                "success": False,
                "error": f"请求异常: {str(e)}"
            }


# 使用示例
if __name__ == "__main__":
    # 创建登录API实例
    login_api = LoginAPI()

    # 执行登录（使用默认账号密码）
    print("正在登录...")
    result = login_api.login("Alltest","Abcd1234.")

